Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix(core): methodsOf filters out getters and symbols #2983

Conversation

LonguCodes
Copy link
Contributor

@LonguCodes LonguCodes commented Feb 6, 2025

Information

fixes #2982

Type Breaking change
Fix No

Todos

  • Tests
  • Coverage
  • Example
  • Documentation

Summary by CodeRabbit

  • New Features

    • Introduced enhanced functionality for extracting defined operations from components, ensuring that only the intended actions are recognized.
  • Tests

    • Added comprehensive unit tests to validate correct extraction across various scenarios, including cases with getter properties.
  • Refactor

    • Improved internal filtering to ignore unintended elements, bolstering overall reliability and consistency in behavior identification.

Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

This change adds unit tests and modifies the methodsOf function. The tests verify that methodsOf correctly returns only method names from a class, even when a property is decorated with @Inject(). In the implementation, the logic now excludes properties that are the constructor, symbols, or properties with a getter (which may result from decorators), ensuring that injected properties do not affect the output.

Changes

File(s) Change Summary
packages/core/.../methodsOf.ts Modified methodsOf to exclude the "constructor", symbol properties, and properties with getters; added import for the isSymbol function.
packages/core/.../methodsOf.spec.ts Added unit tests for methodsOf covering both standard class methods and classes with @Inject-decorated properties to ensure correct filtering.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Suite
    participant Func as methodsOf()
    Test->>Func: Call methodsOf(TestClass)
    Func->>Func: Iterate over class properties
    alt Property is "constructor" / is a symbol / has getter
      Func-->>Func: Skip property
    else Valid method property
      Func-->>Func: Add property to results
    end
    Func->>Test: Return list of method names
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure methodsOf filters out properties transformed by @Inject ([#2982])

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8580b1a and dfb10ec.

📒 Files selected for processing (2)
  • packages/core/src/utils/objects/methodsOf.spec.ts (1 hunks)
  • packages/core/src/utils/objects/methodsOf.ts (2 hunks)
🧰 Additional context used
🪛 ESLint
packages/core/src/utils/objects/methodsOf.spec.ts

[error] 1-3: Run autofix to sort these imports!

(simple-import-sort/imports)

🪛 GitHub Check: lint (20.12.2)
packages/core/src/utils/objects/methodsOf.spec.ts

[failure] 1-1:
Run autofix to sort these imports!

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test-third-parties (20.12.2)
  • GitHub Check: test-security (20.12.2)
  • GitHub Check: test-platform (20.12.2)
  • GitHub Check: test-orm (20.12.2)
  • GitHub Check: test-graphql (20.12.2)
  • GitHub Check: test-core (20.12.2)
  • GitHub Check: test-specs (20.12.2)
🔇 Additional comments (3)
packages/core/src/utils/objects/methodsOf.spec.ts (2)

5-18: Well-structured test case for basic method retrieval!

The test case effectively verifies that methodsOf correctly identifies and returns only method names from a class, excluding regular properties.


19-33: Excellent test coverage for injected properties!

The test case thoroughly verifies that properties decorated with @Inject() are correctly excluded from the method list, which is crucial for the fix.

packages/core/src/utils/objects/methodsOf.ts (1)

4-4: LGTM!

The new import is correctly added and used in the implementation.

import {isSymbol, isSymbolOrSymbolClass} from "./isSymbol.js";
import {methodsOf} from "./methodsOf.js";
import {Inject} from "@tsed/di";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Sort imports according to the project's conventions.

The static analysis tools indicate that imports need to be sorted.

Apply this diff to sort the imports:

-import {isSymbol, isSymbolOrSymbolClass} from "./isSymbol.js";
-import {methodsOf} from "./methodsOf.js";
-import {Inject} from "@tsed/di";
+import {Inject} from "@tsed/di";
+import {isSymbol, isSymbolOrSymbolClass} from "./isSymbol.js";
+import {methodsOf} from "./methodsOf.js";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import {isSymbol, isSymbolOrSymbolClass} from "./isSymbol.js";
import {methodsOf} from "./methodsOf.js";
import {Inject} from "@tsed/di";
import {Inject} from "@tsed/di";
import {isSymbol, isSymbolOrSymbolClass} from "./isSymbol.js";
import {methodsOf} from "./methodsOf.js";
🧰 Tools
🪛 ESLint

[error] 1-3: Run autofix to sort these imports!

(simple-import-sort/imports)

🪛 GitHub Check: lint (20.12.2)

[failure] 1-1:
Run autofix to sort these imports!

Comment on lines +19 to +21
if (isSymbol(propertyKey) || propertyKey === "constructor" || Object.getOwnPropertyDescriptor(prototypeOf(target), propertyKey)?.get)
return;
methods.set(propertyKey, {target, propertyKey});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider improving readability of the filtering condition.

While the implementation is correct, the condition could be more readable by splitting it into separate checks with descriptive variable names.

Consider this refactoring for improved readability:

-      if (isSymbol(propertyKey) || propertyKey === "constructor" || Object.getOwnPropertyDescriptor(prototypeOf(target), propertyKey)?.get)
-        return;
-      methods.set(propertyKey, {target, propertyKey});
+      const descriptor = Object.getOwnPropertyDescriptor(prototypeOf(target), propertyKey);
+      const isGetter = descriptor?.get !== undefined;
+      const isConstructor = propertyKey === "constructor";
+      
+      if (isSymbol(propertyKey) || isConstructor || isGetter) {
+        return; // Skip symbols, constructor, and getter properties
+      }
+      
+      methods.set(propertyKey, {target, propertyKey});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isSymbol(propertyKey) || propertyKey === "constructor" || Object.getOwnPropertyDescriptor(prototypeOf(target), propertyKey)?.get)
return;
methods.set(propertyKey, {target, propertyKey});
const descriptor = Object.getOwnPropertyDescriptor(prototypeOf(target), propertyKey);
const isGetter = descriptor?.get !== undefined;
const isConstructor = propertyKey === "constructor";
if (isSymbol(propertyKey) || isConstructor || isGetter) {
return; // Skip symbols, constructor, and getter properties
}
methods.set(propertyKey, {target, propertyKey});

@LonguCodes LonguCodes force-pushed the fix-methods-of-inject-getter-filterout branch from dfb10ec to 3407640 Compare February 6, 2025 16:03
@LonguCodes LonguCodes force-pushed the fix-methods-of-inject-getter-filterout branch from 3407640 to ba03b92 Compare February 6, 2025 16:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3407640 and ba03b92.

📒 Files selected for processing (2)
  • packages/core/src/utils/objects/methodsOf.spec.ts (1 hunks)
  • packages/core/src/utils/objects/methodsOf.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test-third-parties (20.12.2)
  • GitHub Check: test-specs (20.12.2)
  • GitHub Check: test-security (20.12.2)
  • GitHub Check: test-platform (20.12.2)
  • GitHub Check: test-orm (20.12.2)
  • GitHub Check: test-core (20.12.2)
  • GitHub Check: test-graphql (20.12.2)
🔇 Additional comments (3)
packages/core/src/utils/objects/methodsOf.spec.ts (1)

3-16: LGTM! Good test coverage for basic method detection.

The test effectively verifies that methodsOf correctly identifies methods while excluding regular properties.

packages/core/src/utils/objects/methodsOf.ts (2)

4-4: LGTM! Clean import.


19-21: Verify the filtering implementation.

The filtering logic looks correct but let's verify the implementation handles all edge cases.

Let's check how this implementation is used across the codebase:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check usage patterns of methodsOf and potential edge cases

# Search for methodsOf usage
echo "=== methodsOf usage ==="
rg "methodsOf\(" -A 3

# Search for classes with Symbol methods
echo -e "\n=== Classes with Symbol methods ==="
ast-grep --pattern 'class $_ {
  [$_]() {
    $$$
  }
}'

# Search for classes with getters
echo -e "\n=== Classes with getters ==="
ast-grep --pattern 'class $_ {
  get $_() {
    $$$
  }
}'

Length of output: 3451


The filtering logic in methodsOf.ts has been verified and handles all intended edge cases.

  • The implementation correctly filters out symbol properties, class constructors, and properties with getters.
  • Usage across the codebase (e.g., in decorators and tests) confirms that only valid methods are retained.

Comment on lines +17 to +32
it("should not return getters", () => {
class TestClass {
method() {}

get property() {
return "";
}
}

const methods = methodsOf(TestClass);

expect(methods).toHaveLength(1);
expect(methods[0]).toMatchObject({
propertyKey: "method"
});
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider adding more test cases for comprehensive coverage.

While the getter test is good, consider adding tests for:

  • Symbol methods
  • Constructor method
  • Multiple methods in a class
  • Inherited methods from parent classes

Here's a suggested test case for symbols and inheritance:

it("should handle symbols and inheritance", () => {
  const symbolMethod = Symbol("symbolMethod");
  
  class ParentClass {
    parentMethod() {}
  }
  
  class TestClass extends ParentClass {
    [symbolMethod]() {}
    method() {}
  }

  const methods = methodsOf(TestClass);
  
  expect(methods).toHaveLength(2);
  expect(methods.map(m => m.propertyKey)).toEqual(["method", "parentMethod"]);
});

@Romakita Romakita merged commit d33674d into tsedio:production Feb 6, 2025
12 checks passed
@Romakita
Copy link
Collaborator

Romakita commented Feb 6, 2025

🎉 This PR is included in version 8.4.7 🎉

The release is available on:

Your semantic-release bot 📦🚀

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] UseAuth incompatibile with @Inject decorator
2 participants